function out = get_subwindow(im, pos, window_sz, model_sz)

if isscalar(window_sz),  %square sub-window
    window_sz = [window_sz, window_sz];
end

xs = floor(pos(2)) + (1:window_sz(2)) - floor(window_sz(2)/2);
ys = floor(pos(1)) + (1:window_sz(1)) - floor(window_sz(1)/2);

%check for out-of-bounds coordinates, and set them to the values at
%the borders
xs(xs < 1) = 1;
ys(ys < 1) = 1;
xs(xs > size(im,2)) = size(im,2);
ys(ys > size(im,1)) = size(im,1);

%extract image
patch = im(ys, xs, :);
out = mexResize(patch, model_sz);
end

